<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>共享出行系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .header {
            background-color: #007bff;
            color: white;
            padding: 0 20px;
            height: 50px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            margin: 0;
            font-size: 1.2rem;
        }
        .nav-buttons {
            display: flex;
            gap: 10px;
        }
        .nav-button {
            background: transparent;
            border: 1px solid rgba(255, 255, 255, 0.5);
            border-radius: 4px;
            color: white;
            padding: 6px 12px;
            cursor: pointer;
            transition: background-color 0.2s;
            font-size: 14px;
        }
        .nav-button:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }
        .username {
            margin-right: 15px;
            font-size: 14px;
        }
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 0 15px;
        }
        .filter-container {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            justify-content: flex-start;
        }
        .filter-select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-width: 120px;
        }
        .vehicle-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }
        .vehicle-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .vehicle-header {
            padding: 12px 15px;
            border-bottom: 1px solid #f0f0f0;
            font-weight: bold;
        }
        .vehicle-content {
            padding: 15px;
        }
        .vehicle-tags {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }
        .vehicle-tag {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
        }
        .vehicle-price {
            color: #ff6600;
            font-weight: bold;
            float: right;
        }
        .car-tag { background: #e3f2fd; color: #1976d2; }
        .ebike-tag { background: #e8f5e9; color: #2e7d32; }
        .bicycle-tag { background: #fff3e0; color: #e65100; }
        .available-tag { background: #e8f5e9; color: #2e7d32; }
        .in-use-tag { background: #fff3e0; color: #e65100; }
        .vehicle-detail {
            margin: 5px 0;
        }
        .vehicle-location {
            font-size: 13px;
            color: #666;
            margin: 10px 0;
        }
        .rent-button {
            width: 100%;
            padding: 10px;
            background: #007bff;
            border: none;
            border-radius: 4px;
            color: white;
            font-weight: bold;
            cursor: pointer;
            transition: background 0.2s;
        }
        .rent-button:hover {
            background: #0056b3;
        }
        .rent-button:disabled {
            background: #cccccc;
            cursor: not-allowed;
        }
        /* Modal styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            position: relative;
            background-color: white;
            margin: 10% auto;
            padding: 20px;
            width: 80%;
            max-width: 500px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }
        .close {
            position: absolute;
            right: 20px;
            top: 10px;
            font-size: 28px;
            font-weight: bold;
            color: #aaa;
            cursor: pointer;
        }
        .toast {
            position: fixed;
            bottom: 30px;
            right: 30px;
            background: #4caf50;
            color: white;
            padding: 15px 25px;
            border-radius: 4px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            z-index: 1010;
            opacity: 0;
            transform: translateY(20px);
            transition: opacity 0.3s, transform 0.3s;
        }
        .toast.show {
            opacity: 1;
            transform: translateY(0);
        }
        .toast.error {
            background: #f44336;
        }
        .loading {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255,255,255,0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1020;
            display: none;
        }
        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>共享出行系统</h1>
        <div class="nav-buttons">
            <span class="username" id="usernameDisplay"></span>
            <button class="nav-button" onclick="window.location.href='vehicle-management.html'" id="adminButton" style="display: none;">车辆管理</button>
            <button class="nav-button" onclick="window.location.href='edit-profile.html'">个人资料</button>
            <button class="nav-button" onclick="logout()">退出登录</button>
        </div>
    </div>

    <div class="container">
        <div class="filter-container">
            <select id="typeFilter" class="filter-select" onchange="applyFilters()">
                <option value="">所有类型</option>
                <option value="car">汽车</option>
                <option value="e-bike">电动车</option>
                <option value="bicycle">自行车</option>
            </select>
            
            <select id="sortFilter" class="filter-select" onchange="applyFilters()">
                <option value="price_asc">价格从低到高</option>
                <option value="price_desc">价格从高到低</option>
            </select>
        </div>

        <div id="vehicleGrid" class="vehicle-grid">
            <!-- 车辆卡片将通过JavaScript动态添加 -->
        </div>
    </div>

    <!-- 租赁确认模态框 -->
    <div id="rentalModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeRentalModal()">&times;</span>
            <div class="modal-header">
                <h2>确认租赁</h2>
            </div>
            <div class="modal-body">
                <h3 id="rentalVehicleName"></h3>
                <p id="rentalVehicleDetails"></p>
                <p id="rentalPriceInfo" style="color: #ff6600; font-weight: bold;"></p>
                <p>确认租赁后，您需要负责车辆的安全，并按时归还。</p>
            </div>
            <div class="modal-footer">
                <button class="nav-button" style="background: #ddd; color: #333;" onclick="closeRentalModal()">取消</button>
                <button class="nav-button" style="background: #007bff;" onclick="confirmRental()">确认租赁</button>
            </div>
        </div>
    </div>

    <!-- 租赁成功模态框 -->
    <div id="successModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="document.getElementById('successModal').style.display = 'none'">&times;</span>
            <div class="modal-header">
                <h2>租赁成功</h2>
            </div>
            <div class="modal-body">
                <p>您已成功租赁车辆。</p>
                <p>租赁开始时间: <span id="rentalStartTime"></span></p>
                <p>请记得使用完毕后归还车辆。</p>
            </div>
            <div class="modal-footer">
                <button class="nav-button" style="background: #007bff;" onclick="window.location.href='trip.html'">查看行程</button>
                <button class="nav-button" style="background: #ddd; color: #333;" onclick="document.getElementById('successModal').style.display = 'none'">关闭</button>
            </div>
        </div>
    </div>

    <div id="toast" class="toast"></div>
    
    <div class="loading">
        <div class="spinner"></div>
    </div>

    <script>
        // 全局变量
        let allVehicles = [];
        let filteredVehicles = [];
        let selectedVehicleId = null;
        let userLocation = null;

        // 初始化
        document.addEventListener('DOMContentLoaded', async () => {
            await checkLogin();
            getUserLocation();
            await fetchVehicles();
        });

        // 获取用户位置
        function getUserLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    (position) => {
                        userLocation = {
                            lat: position.coords.latitude,
                            lng: position.coords.longitude
                        };
                    },
                    (error) => {
                        console.error('获取位置失败:', error);
                        userLocation = { lat: 30.274084, lng: 120.155070 }; // 默认位置：杭州
                        showToast('无法获取您的位置，使用默认位置', true);
                    }
                );
            } else {
                userLocation = { lat: 30.274084, lng: 120.155070 }; // 默认位置：杭州
                showToast('您的浏览器不支持地理位置功能', true);
            }
        }

        // 检查登录状态
        async function checkLogin() {
            showLoading();
            try {
                const response = await fetch('api/check-login', {
                    credentials: 'include'
                });
                const result = await response.json();
                
                if (!result.success) {
                    window.location.href = 'login.html';
                    return false;
                }
                
                // 显示用户信息
                document.getElementById('usernameDisplay').textContent = result.data.username;
                
                // 检查管理员权限
                if (result.data.role === 'admin') {
                    document.getElementById('adminButton').style.display = 'inline-block';
                }
                
                hideLoading();
                return true;
            } catch (error) {
                console.error('检查登录状态失败:', error);
                hideLoading();
                window.location.href = 'login.html';
                return false;
            }
        }

        // 获取车辆列表
        async function fetchVehicles() {
            showLoading();
            try {
                const response = await fetch('api/vehicles', {
                    credentials: 'include'
                });
                const result = await response.json();
                
                if (result.success) {
                    allVehicles = result.data;
                    applyFilters();
                } else {
                    showToast('获取车辆列表失败: ' + result.message, true);
                }
                hideLoading();
            } catch (error) {
                console.error('获取车辆列表失败:', error);
                showToast('获取车辆列表失败，请稍后重试', true);
                hideLoading();
            }
        }

        // 应用筛选条件
        function applyFilters() {
            const typeFilter = document.getElementById('typeFilter').value;
            const sortFilter = document.getElementById('sortFilter').value;
            
            filteredVehicles = allVehicles.filter(vehicle => {
                if (typeFilter && vehicle.type !== typeFilter) {
                    return false;
                }
                return true;
            });
            
            // 排序
            filteredVehicles.sort((a, b) => {
                if (sortFilter === 'price_asc') {
                    return a.pricePerMinute - b.pricePerMinute;
                } else if (sortFilter === 'price_desc') {
                    return b.pricePerMinute - a.pricePerMinute;
                }
                return 0;
            });
            
            renderVehicles();
        }

        // 渲染车辆列表
        function renderVehicles() {
            const vehicleGrid = document.getElementById('vehicleGrid');
            let html = '';
            
            if (filteredVehicles.length === 0) {
                html = '<div style="grid-column: 1/-1; text-align: center; padding: 50px 0;">没有符合条件的车辆</div>';
            } else {
                filteredVehicles.forEach(vehicle => {
                    const isAvailable = vehicle.status === 0;
                    const typeText = getTypeText(vehicle.type);
                    const typeClass = getTypeClass(vehicle.type);
                    const statusText = getStatusText(vehicle.status);
                    const statusClass = getStatusClass(vehicle.status);
                    
                    html += `
                        <div class="vehicle-card">
                            <div class="vehicle-header">
                                ${typeText} - ${vehicle.plateNumber}
                            </div>
                            <div class="vehicle-content">
                                <div class="vehicle-tags">
                                    <span class="vehicle-tag ${typeClass}">${typeText}</span>
                                    <span class="vehicle-tag ${statusClass}">${statusText}</span>
                                    <span class="vehicle-price">¥${vehicle.pricePerMinute}/分钟</span>
                                </div>
                                <div class="vehicle-detail">品牌型号: ${vehicle.brand} ${vehicle.model}</div>
                                <div class="vehicle-location">位置: 经度: ${vehicle.longitude}, 纬度: ${vehicle.latitude}</div>
                                <button class="rent-button" onclick="openRentalModal(${vehicle.id})" ${isAvailable ? '' : 'disabled'}>
                                    ${isAvailable ? '立即租用' : '不可用'}
                                </button>
                            </div>
                        </div>
                    `;
                });
            }
            
            vehicleGrid.innerHTML = html;
        }

        // 打开租赁确认模态框
        function openRentalModal(vehicleId) {
            const vehicle = filteredVehicles.find(v => v.id === vehicleId);
            if (!vehicle) return;
            
            selectedVehicleId = vehicleId;
            
            document.getElementById('rentalVehicleName').textContent = `${getTypeText(vehicle.type)} ${vehicle.plateNumber}`;
            document.getElementById('rentalVehicleDetails').textContent = `${vehicle.brand} ${vehicle.model}`;
            document.getElementById('rentalPriceInfo').textContent = `费用: ¥${vehicle.pricePerMinute}/分钟`;
            
            document.getElementById('rentalModal').style.display = 'block';
        }

        // 关闭租赁确认模态框
        function closeRentalModal() {
            document.getElementById('rentalModal').style.display = 'none';
            selectedVehicleId = null;
        }

        // 确认租赁
        async function confirmRental() {
            if (!selectedVehicleId) return;
            
            showLoading();
            try {
                const response = await fetch('api/rental/start', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        vehicleId: selectedVehicleId
                    }),
                    credentials: 'include'
                });
                
                const result = await response.json();
                
                if (result.success) {
                    closeRentalModal();
                    document.getElementById('rentalStartTime').textContent = new Date().toLocaleString();
                    document.getElementById('successModal').style.display = 'block';
                    
                    // 重新获取车辆列表以更新状态
                    await fetchVehicles();
                } else {
                    showToast(result.message || '租赁失败', true);
                }
            } catch (error) {
                console.error('租赁请求失败:', error);
                showToast('租赁请求失败，请稍后重试', true);
            } finally {
                hideLoading();
            }
        }

        // 退出登录
        async function logout() {
            showLoading();
            try {
                const response = await fetch('api/logout', {
                    method: 'POST',
                    credentials: 'include'
                });
                const result = await response.json();
                
                if (result.success) {
                    window.location.href = 'login.html';
                } else {
                    showToast('退出失败: ' + result.message, true);
                }
            } catch (error) {
                console.error('退出失败:', error);
                showToast('退出失败，请稍后重试', true);
            } finally {
                hideLoading();
            }
        }

        // 工具函数：获取车辆类型文本
        function getTypeText(type) {
            switch (type) {
                case 'car': return '汽车';
                case 'e-bike': return '电动车';
                case 'bicycle': return '自行车';
                default: return type;
            }
        }

        // 工具函数：获取车辆类型样式类
        function getTypeClass(type) {
            switch (type) {
                case 'car': return 'car-tag';
                case 'e-bike': return 'ebike-tag';
                case 'bicycle': return 'bicycle-tag';
                default: return '';
            }
        }

        // 工具函数：获取状态文本
        function getStatusText(status) {
            switch (status) {
                case 0: return '可用';
                case 1: return '使用中';
                case 2: return '维护中';
                default: return '未知';
            }
        }

        // 工具函数：获取状态样式类
        function getStatusClass(status) {
            switch (status) {
                case 0: return 'available-tag';
                case 1: return 'in-use-tag';
                default: return '';
            }
        }

        // 显示消息提示
        function showToast(message, isError = false) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = 'toast';
            if (isError) {
                toast.classList.add('error');
            }
            toast.classList.add('show');
            
            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }

        // 显示加载动画
        function showLoading() {
            document.querySelector('.loading').style.display = 'flex';
        }

        // 隐藏加载动画
        function hideLoading() {
            document.querySelector('.loading').style.display = 'none';
        }
    </script>
</body>
</html> 